<?php

namespace Biz\module\Classes\wiki;

use Biz\cache\wiki\JdUnionUrl as cJdUnionUrl;
use Biz\cache\wiki\MechanicUserImg;
use Biz\cache\wiki\TbkUrl as cTbkUrl;
use Biz\model\brandAccount\BrandAccountInfo;
use Biz\model\brandAccount\BrandAccountShop;
use Biz\model\wiki\ObjRelateWiki as mObjRelateWiki;
use Biz\model\wiki\Wiki as mWiki;
use Biz\model\wiki\WikiAbnormalLog;
use Biz\model\wiki\WikiBasic as mWikiBasic;
use Biz\model\wiki\WikiContent as mWikiContent;
use Biz\module\Classes\wiki\Wiki as clsWiki;
use Biz\pockets\serviceTrait\_Async;
use Biz\scraper\GoodsInfo as scraperGoodsInfo;
use Biz\service\brandAccount\BrandAccount;
use Biz\service\LinkCleaning\TaskCallbackInitWiki;
use Biz\tools\helper\Common;
use Biz\tools\JdUnion;
use Biz\tools\KaoLa;
use Biz\tools\OneBound;
use Biz\tools\RealUrl;
use Biz\tools\SuNing;
use Biz\tools\TbkUnion;
use Doraemon\cache\Queue;
use Doraemon\model\CommentLink as mCommentLink;
use Doraemon\model\Member;
use Doraemon\model\Store\ShenJianGoods as mShenJianGoods;
use Doraemon\service\User;
use Doraemon\tools\Log;
use Doraemon\tools\Youzan;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\newCache;

class Wiki
{

    use _Async;

    /**
     * 根据链接获取wiki信息
     * @param $content
     * @param int $objType
     * @param null $objId
     * @param bool $isPreCreate (预创建，没抓取到的时候先创建wiki)
     * @return array|false|mixed
     * @throws \Exception
     */
    public static function getWikiByContent($content, $objType = 1, $objId = null, $isPreCreate = true)
    {
        $addTask = false;
        $sign = [
            'obj_type' => $objType,
            'obj_id' => $objId
        ];
        $wikiInfo = [];
        list($scraperWikiInfo, $itemId, $channelType) = scraperGoodsInfo::getGoodsInfo($content);
        if ($scraperWikiInfo) {
            $channelType = $scraperWikiInfo['channel_type'];
            $channel = clsWiki::getChannel($channelType);
            if (!$channel) {
                Log::wiki_getWikiByLink_warning('抓取链接获取的channel不正确#channel_type:' . $scraperWikiInfo['channel_type'] . '#channel:' . $channel);
                return false;
            }
            $scraperWikiInfo['channel'] = $channel;
            $wikiInfo = mWiki::getInfoByChannelSpu($scraperWikiInfo['channel'], $scraperWikiInfo['channel_spu_id']);
            if (!empty($wikiInfo)) {
                $wikiId = $wikiInfo['id'];
                $wikiContentInfo = mWikiContent::getByWikiId($wikiInfo['id']);
                $wikiData = [];
                $wikiContentData = [];
                $changeKey = ["title", "cover_img", "channel_seller_id", "channel_shop_id", "channel_shop_name", "channel_category_name", "min_price", "max_price", "channel_jump_params", "tags", "channel_spu_status"];
                foreach ($wikiInfo as $key => $val) {
                    if (in_array($key, $changeKey)) {
                        if ($key == 'min_price' || $key == 'max_price') {
                            if ($val <= 0) {
                                $wikiData[$key] = (isset($scraperWikiInfo[$key]) && $scraperWikiInfo[$key]) ? $scraperWikiInfo[$key] : $wikiInfo[$key];
                                $wikiInfo[$key] = (isset($scraperWikiInfo[$key]) && $scraperWikiInfo[$key]) ? $scraperWikiInfo[$key] : $wikiInfo[$key];
                            }
                        } else if ($key == 'channel_spu_status') {
                            $wikiData[$key] = isset($scraperWikiInfo[$key]) ? $scraperWikiInfo[$key] : $wikiInfo[$key];
                            $wikiInfo[$key] = isset($scraperWikiInfo[$key]) ? $scraperWikiInfo[$key] : $wikiInfo[$key];
                        } else if (empty($val)) {
                            $wikiData[$key] = (isset($scraperWikiInfo[$key]) && $scraperWikiInfo[$key]) ? $scraperWikiInfo[$key] : $wikiInfo[$key];
                            $wikiInfo[$key] = (isset($scraperWikiInfo[$key]) && $scraperWikiInfo[$key]) ? $scraperWikiInfo[$key] : $wikiInfo[$key];
                        }
                    }
                }
                if (bccomp($wikiInfo['min_price'], $wikiInfo['max_price'], 2) == 0) {
                    if ((isset($scraperWikiInfo['min_price']) && $scraperWikiInfo['min_price'] > 0)) {
                        $wikiInfo['min_price'] = $scraperWikiInfo['min_price'];
                        $wikiData['min_price'] = $scraperWikiInfo['min_price'];
                    }
                    if ((isset($scraperWikiInfo['max_price']) && $scraperWikiInfo['max_price'] > 0)) {
                        $wikiInfo['max_price'] = $scraperWikiInfo['max_price'];
                        $wikiData['max_price'] = $scraperWikiInfo['max_price'];
                    }
                }
                if (!isset($wikiContentInfo['imgs']) || !$wikiContentInfo['imgs']) {
                    $wikiContentData['imgs'] = (isset($scraperWikiInfo['imgs']) && $scraperWikiInfo['imgs']) ? $scraperWikiInfo['imgs'] : '';
                }
                if (!isset($wikiContentInfo['content']) || !$wikiContentInfo['content']) {
                    $wikiContentData['content'] = (isset($scraperWikiInfo['content']) && $scraperWikiInfo['content']) ? $scraperWikiInfo['content'] : '';
                }
                if (!$scraperWikiInfo['title'] || !$scraperWikiInfo['cover_img']
                    || (!$scraperWikiInfo['channel_shop_id'] && !$scraperWikiInfo['channel_seller_id']) || !$scraperWikiInfo['channel_shop_name']
                    || $scraperWikiInfo['min_price'] <= 0 || $scraperWikiInfo['max_price'] <= 0
                    || !$scraperWikiInfo['imgs'] || !$scraperWikiInfo['content']) {
                    if ($wikiInfo['status'] == mWiki::STATUS_NORMAL || !$wikiInfo['title']) {//待完善wiki信息状态，重新添加抓取任务
                        //添加抓取wiki任务
                        $addTask = true;
                    }
                    if (!$scraperWikiInfo['channel_shop_name'] && !$wikiInfo['channel_shop_name']) {
                        $addTask = true;
                    }
                    if (!isset($wikiData['status']) && $wikiInfo['status'] == mWiki::STATUS_DEL) {
                        $wikiData['status'] = mWiki::STATUS_NORMAL;
                    }
                } else {
                    $wikiData['status'] = mWiki::STATUS_WAIT_CHECK;
                }
                if ($wikiData) {
                    mWiki::updateData($wikiData, ['id' => $wikiInfo['id']]);
                }
                if ($wikiContentData) {
                    if (!$wikiContentInfo) {
                        $wikiContentData['wiki_id'] = $wikiInfo['id'];
                        mWikiContent::insertData($wikiContentData);
                    } else {
                        mWikiContent::updateData($wikiContentData, ['wiki_id' => $wikiInfo['id']]);
                    }
                }

                self::cleanedWiki($wikiInfo['id'], $objId, $objType);
                //添加basic info
                if ($wikiInfo['basic_id']) {
                    $basicInfo = mWikiBasic::getByWhere([
                        'id' => $wikiInfo['basic_id'],
                        'basic_state[!]' => mWikiBasic::STATE_DEL
                    ]);
                    if ($basicInfo && is_array($basicInfo)) {
                        $wikiInfo['basic_id'] = $basicInfo['id'];
                        $wikiInfo['basic_title'] = $basicInfo['title'];
                        $wikiInfo['basic_state'] = $basicInfo['basic_state'];
                    };
                }
                //添加basic info
            } else {
                $scraperWikiInfo['status'] = mWiki::STATUS_NORMAL;
                $scraperWikiInfo['addtime'] = date('Y-m-d H:i:s');
                $scraperWikiInfo['edittime'] = date('Y-m-d H:i:s');
                $wikiData = $scraperWikiInfo;
                if ($scraperWikiInfo['channel_shop_id']) {
                    if (in_array($channelType, [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL])) {
                        $accountShopInfo = BrandAccountShop::getInfoByShopId($scraperWikiInfo['channel_shop_id'], [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL]);
                        if ($accountShopInfo) {
                            $accountId = $accountShopInfo['account_id'];
                            $accountInfo = $accountId ? BrandAccount::getAccountInfoById($accountId) : [];
                            if ($accountInfo && $scraperWikiInfo['channel_shop_id'] == $accountShopInfo['shop_id']) {
                                $wikiData['shop_uid'] = $accountInfo['uid'];
                            }
                        }
                    }
                }

                $wikiBasicData = [
                    'brand_id' => 0,
                    'title' => !empty($wikiData['title']) ? $wikiData['title'] : '',
                    'basic_state' => mWikiBasic::STATE_NORMAL,
                ];
                $basicId = mWikiBasic::insertData($wikiBasicData);
                if ($basicId) {
                    if (!$scraperWikiInfo['title'] || !$scraperWikiInfo['cover_img']
                        || (!$scraperWikiInfo['channel_shop_id'] && !$scraperWikiInfo['channel_seller_id'])
                        || !$scraperWikiInfo['channel_shop_name']
                        || $scraperWikiInfo['min_price'] <= 0 || $scraperWikiInfo['max_price'] <= 0
                        || !$scraperWikiInfo['imgs'] || !$scraperWikiInfo['content']) {
                        //添加抓取wiki任务
                        $addTask = true;
                    } else {
                        $wikiData['status'] = mWiki::STATUS_WAIT_CHECK;
                    }
                    $wikiData['basic_id'] = $basicId;
                    $wikiData['source_basic_id'] = $basicId;
                    $wikiData['is_default'] = 1;
                    unset($wikiData['channel_spu_status']);
                    unset($wikiData['imgs']);
                    unset($wikiData['content']);
                    $wikiId = mWiki::insertData($wikiData);
                    if ($wikiId) {
                        $wikiInfo = $wikiData;
                        $wikiInfo['id'] = $wikiId;
                        $contentData['wiki_id'] = $wikiId;
                        if (isset($scraperWikiInfo['imgs'])) {
                            $contentData['imgs'] = $scraperWikiInfo['imgs'];
                        }
                        if (isset($scraperWikiInfo['content'])) {
                            $contentData['content'] = $scraperWikiInfo['content'];
                        }
                        mWikiContent::insertData($contentData);

                        if (isset($scraperWikiInfo['title']) && $scraperWikiInfo['title']) {
                            $wikiInfo['title'] = $scraperWikiInfo['title'];
                            $wikiInfo['channel_category_name'] = $scraperWikiInfo['channel_category_name'];
                        }
                        self::cleanedWiki($wikiInfo['id'], $objId, $objType);

                        //添加basic info
                        $wikiInfo['basic_id'] = $basicId;
                        $wikiInfo['basic_title'] = $wikiData['title'];
                        $wikiInfo['basic_state'] = mWikiBasic::STATE_NORMAL;
                        //添加basic info
                    } else {
                        Log::wiki_getWikiByLink_warning('添加wiki失败#' . json_encode($scraperWikiInfo, true) . '#sql:' . json_encode(mWiki::log(), true));
                        $wikiInfo = [];
                        //添加抓取wiki任务
                        $addTask = true;
                    }
                } else {
                    Log::wiki_getWikiByLink_warning('添加wiki basic失败#' . json_encode($scraperWikiInfo, true) . '#sql:' . json_encode(mWikiBasic::log(), true));
                    $wikiInfo = [];
                    //添加抓取wiki任务
                    $addTask = true;
                }
            }
            $isAbnormal = (isset($scraperWikiInfo['channel_spu_status']) && $scraperWikiInfo['channel_spu_status'] == 0) ? true : false;
            //记录重新抓取失败的wiki
            WikiAbnormalLog::updateAbnormalCount($wikiId, $isAbnormal);
        } else if ($channelType && $itemId) {
            $channel = self::getChannel($channelType);
            $wikiInfo = mWiki::getInfoByChannelSpu($channel, $itemId);
            if (empty($wikiInfo)) {
                $addTask = true;
                if ($isPreCreate) {//预创建。如果没有抓取到，先创建一个wiki
                    $wikiBasicData = [
                        'brand_id' => 0,
                        'title' => '',
                        'basic_state' => mWikiBasic::STATE_NORMAL,
                    ];
                    $basicId = mWikiBasic::insertData($wikiBasicData);
                    if ($basicId) {
                        $wikiData = [
                            'channel' => $channel,
                            'channel_type' => $channelType,
                            'channel_spu_id' => $itemId,
                            'status' => mWiki::STATUS_NORMAL,
                            'basic_id' => $basicId,
                            'source_basic_id' => $basicId,
                            'is_default' => 1,
                        ];
                        $wikiId = mWiki::insertData($wikiData);
                        if ($wikiId) {
                            $wikiInfo = $wikiData;
                            $wikiInfo['id'] = $wikiId;
                            $wikiInfo['basic_state'] = mWikiBasic::STATE_NORMAL;
                        }
                    }
                }
            } else {
                if (!$wikiInfo['title'] || !$wikiInfo['cover_img']
                    || (!$wikiInfo['channel_shop_id'] && !$wikiInfo['channel_seller_id'])
                    || !$wikiInfo['channel_shop_name']
                    || $wikiInfo['min_price'] <= 0 || $wikiInfo['max_price'] <= 0) {
                    if ($wikiInfo['status'] == mWiki::STATUS_NORMAL || !$wikiInfo['title']) {//待完善wiki信息状态，重新添加抓取任务
                        //添加抓取wiki任务
                        $addTask = true;
                    }
                }
            }
            $wikiInfo = !empty($wikiInfo) ? $wikiInfo : [];
        } else {
            $wikiInfo = null;
        }
        if ($addTask && $channel != mWiki::CHANNEL_TYPE_YOUZAN) {//有赞不支持网多云抓取
            if ($wikiInfo && ($channel == mWiki::CHANNEL_TAOBAO)) {
                scraperGoodsInfo::addOneBoundTask($wikiInfo['id']);
            } else {
                scraperGoodsInfo::addTask($sign, $content, TaskCallbackInitWiki::class);
            }
        }
        if ($wikiInfo) {
            if (!isset($wikiInfo['title']) || !isset($wikiInfo['cover_img']) || !$wikiInfo['title'] || !$wikiInfo['cover_img']) {
                if ($isPreCreate) {
                    $wikiInfo['tips'] = ['text' => '商品信息正在解析中...'];
                } else {
                    $wikiInfo = [];
                }
            }
            if (!isset($wikiInfo['title']) || !$wikiInfo['title']) {
                if ($isPreCreate) {
                    $wikiInfo['title'] = clsWiki::getDefaultTitle($channelType);
                } else {
                    $wikiInfo = [];
                }
            }
        }
        return $wikiInfo;
    }

    public static function updateByOneBound($wikiInfo)
    {
        if ($wikiInfo && $wikiInfo['channel'] == mWiki::CHANNEL_TAOBAO) {
            $oneBoundInfo = OneBound::getTaoBaoItemInfo($wikiInfo['channel_spu_id'], $wikiInfo['channel_type']);
            $wikiData = [];
            $wikiContentData = [];
            $changeKey = ["title", "cover_img", "channel_seller_id", "channel_shop_id", "channel_shop_name", "channel_category_name", "channel_brand", "min_price", "max_price", "tags"];
            foreach ($wikiInfo as $key => $val) {
                if (in_array($key, $changeKey)) {
                    if ($key == 'min_price' || $key == 'max_price') {
                        if ($val <= 0) {
                            $wikiData[$key] = (isset($oneBoundInfo[$key]) && $oneBoundInfo[$key]) ? $oneBoundInfo[$key] : $wikiInfo[$key];
                            $wikiInfo[$key] = (isset($oneBoundInfo[$key]) && $oneBoundInfo[$key]) ? $oneBoundInfo[$key] : $wikiInfo[$key];
                        }
                    } else if (empty($val)) {
                        $wikiData[$key] = (isset($oneBoundInfo[$key]) && $oneBoundInfo[$key]) ? $oneBoundInfo[$key] : $wikiInfo[$key];
                        $wikiInfo[$key] = (isset($oneBoundInfo[$key]) && $oneBoundInfo[$key]) ? $oneBoundInfo[$key] : $wikiInfo[$key];
                    }
                }
            }
            if (bccomp($wikiInfo['min_price'], $wikiInfo['max_price'], 2) == 0) {
                if ($oneBoundInfo) {
                    $wikiInfo['min_price'] = ($oneBoundInfo['min_price'] > 0) ? $oneBoundInfo['min_price'] : $wikiInfo['min_price'];
                    $wikiInfo['max_price'] = ($oneBoundInfo['max_price'] > 0) ? $oneBoundInfo['max_price'] : $wikiInfo['max_price'];
                    $wikiData['min_price'] = ($oneBoundInfo['min_price'] > 0) ? $oneBoundInfo['min_price'] : $wikiInfo['min_price'];
                    $wikiData['max_price'] = ($oneBoundInfo['max_price'] > 0) ? $oneBoundInfo['max_price'] : $wikiInfo['max_price'];
                }
            }
            $wikiContentInfo = mWikiContent::getByWikiId($wikiInfo['id']);
            if (!empty($oneBoundInfo['imgs'])) {
                $wikiContentData['imgs'] = $oneBoundInfo['imgs'];
                $wikiInfo['imgs'] = $oneBoundInfo['imgs'] ? $oneBoundInfo['imgs'] : ($wikiContentInfo ? $wikiContentInfo['imgs'] : '');
            }
            if (!empty($oneBoundInfo['content'])) {
                $wikiContentData['content'] = $oneBoundInfo['content'];
                $wikiInfo['content'] = $oneBoundInfo['content'] ? $oneBoundInfo['content'] : ($wikiContentInfo ? $wikiContentInfo['content'] : '');
            }
            if (!$wikiInfo['title'] || !$wikiInfo['cover_img']
                || (!$wikiInfo['channel_shop_id'] && !$wikiInfo['channel_seller_id'])
                || !$wikiInfo['channel_shop_name']
                || $wikiInfo['min_price'] <= 0 || $wikiInfo['max_price'] <= 0
                || !$wikiInfo['imgs'] || !$wikiInfo['content']) {
            } else {
                $wikiData['status'] = mWiki::STATUS_WAIT_CHECK;
            }
            if ($wikiData) {
                mWiki::updateData($wikiData, ['id' => $wikiInfo['id']]);
            }
            if ($wikiContentData) {
                if (!$wikiContentInfo) {
                    $wikiContentData['wiki_id'] = $wikiInfo['id'];
                    mWikiContent::insertData($wikiContentData);
                } else {
                    mWikiContent::updateData($wikiContentData, ['wiki_id' => $wikiInfo['id']]);
                }
            }
        }
        return $wikiInfo;
    }

    /**
     * 清洗完的数据转换为wiki
     * @param $sign 清洗数据来源
     * @param $cleaningData 清洗的数据
     * @return bool
     * @throws \Exception
     */
    public static function afterCleaningData($sign, $cleaningData)
    {
        try {
            $cleaningData = $cleaningData['goods'];
            Log::wiki_afterCleaning_info('清洗完数据，开始转换为wiki#data:' . json_encode(['sign' => $sign, 'title' => $cleaningData['name'], 'channel_type' => $cleaningData['type'], 'spu_id' => $cleaningData['goods_id']], JSON_UNESCAPED_UNICODE));
            $channelType = $cleaningData['type'];
            $channel = self::getChannel($cleaningData['type']);
            if (!$channel) {
                Log::wiki_afterCleaning_warning('清洗完数据，开始转换为wiki,不存在的channel#channel_type:' . $channelType . '#goods_id:' . $cleaningData['goods_id']);
                return false;
            }
            if (empty($cleaningData) || empty($cleaningData['name'])) {
                return false;
            }
            $data = [
                'title' => $cleaningData['name'],
                'channel' => $channel,
                'channel_type' => $channelType,
                'channel_brand' => $cleaningData['brand'],
                'channel_shop_id' => $cleaningData['shop_id'],
                'channel_shop_name' => $cleaningData['shop_name'],
                'channel_spu_id' => $cleaningData['goods_id'],
                'channel_category_name' => $cleaningData['category'],
                'category_id' => $cleaningData['one_category_id'],
                'second_category_id' => $cleaningData['two_category_id'],
                'last_category_id' => $cleaningData['last_category_id'],
                'cover_img' => isset($cleaningData['images'][0]) ? $cleaningData['images'][0] : '',
                'min_price' => $cleaningData['min_price'],
                'max_price' => $cleaningData['max_price'],
                'status' => mWiki::STATUS_WAIT_CHECK,
            ];
            $wikiData = $data;
            $contentData = [
                'imgs' => isset($cleaningData['images']) ? json_encode($cleaningData['images'], true) : '',
                'content' => $cleaningData['detail'] ? $cleaningData['detail'] : '',
            ];

            $channelArr = in_array($channelType, [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL]) ? [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL] : $channelType;
            $accountShopInfo = BrandAccountShop::getInfoByShopId($cleaningData['shop_id'], $channelArr);
            if ($accountShopInfo) {
                $accountId = $accountShopInfo['account_id'];
                $accountInfo = $accountId ? BrandAccount::getAccountInfoById($accountId) : [];
                if ($accountInfo && $cleaningData['shop_id'] == $accountShopInfo['shop_id']) {
                    $wikiData['shop_uid'] = $accountInfo['uid'];
                }
            }

            $wikiInfo = mWiki::getInfoByChannelSpu($channel, $data['channel_spu_id']);
            if ($wikiInfo) {
                $wikiId = $wikiInfo['id'];
                $changeKey = ["title", "channel_brand", "channel_shop_id", "channel_shop_name", "channel_category_name", "category_id", "second_category_id", "last_category_id", "cover_img"];
                foreach ($wikiInfo as $key => $val) {
                    if (in_array($key, $changeKey)) {
                        if ($val) {
                            unset($wikiData[$key]);
                        }
                    }
                }
                if ($wikiInfo['status'] != mWiki::STATUS_CHECKED) {
                    mWiki::updateData($wikiData, ['id' => $wikiId]);
                }
                $contentInfo = mWikiContent::getByWhere(['wiki_id' => $wikiId]);
                if ($contentInfo) {
                    if ($wikiInfo['status'] != mWiki::STATUS_CHECKED) {
                        if (!$contentData['imgs'] || $contentInfo['imgs']) {
                            unset($contentData['imgs']);
                        }
                        if (!$contentData['content'] || $contentInfo['content']) {
                            unset($contentData['content']);
                        }
                        if ($contentData) {
                            mWikiContent::updateData($contentData, ['wiki_id' => $wikiId]);
                        }
                    }
                } else {
                    $contentData['wiki_id'] = $wikiId;
                    mWikiContent::insertData($contentData);
                }
            } else {
                $wikiBasicData = [
                    'brand_id' => 0,
                    'title' => $wikiData['title'],
                    'basic_state' => mWikiBasic::STATE_NORMAL,
                    'category_id' => $wikiData['category_id'],
                    'second_category_id' => $wikiData['second_category_id'],
                    'last_category_id' => $wikiData['last_category_id'],
                ];
                $basicId = mWikiBasic::insertData($wikiBasicData);
                $wikiData['basic_id'] = $basicId;
                $wikiData['source_basic_id'] = $basicId;
                $wikiData['is_default'] = 1;
                $wikiId = mWiki::insertData($wikiData);
                $contentData['wiki_id'] = $wikiId;
                mWikiContent::insertData($contentData);
            }
            if (!$sign) {
                Log::wiki_afterCleaning_warning('清洗完数据，并已经转换为wiki。参数错误#sign:' . json_encode($sign));
                return false;
            }
            $objId = isset($sign['obj_id']) ? $sign['obj_id'] : null;
            $objType = isset($sign['obj_type']) ? $sign['obj_type'] : null;
            self::cleanedWiki($wikiId, $objId, $objType);
        } catch (\Exception $e) {
            $err = '清洗完数据，处理wiki发生异常#data:' . json_encode(['e_msg' => $e->getMessage(), 'e_code' => $e->getMessage(), 'e_file' => $e->getFile(), 'e_line' => $e->getLine(), 'sign' => $sign, 'clieaningData' => $cleaningData], JSON_UNESCAPED_UNICODE);
            Log::wiki_afterCleaning_info($err);
            \Doraemon\amqp\Queue::insertQueue("queue/Wechatnotice/toTag", [
                "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                "content" => $err
            ], Queue::QUEUE_BIZ);
        }
    }

    /**
     * 清洗完的wiki数据处理
     * 内容处理（更新评论）
     * @param $wikiId
     * @param $objId
     * @param $objType
     */
    public static function cleanedWiki($wikiId, $objId, $objType)
    {
        $where = [
            'wiki_id' => $wikiId,
            'status' => mObjRelateWiki::STATUS_NORMAL
        ];
        if (!is_null($objId) && $objId) {
            $where['obj_id'] = $objId;
        }
        if (!is_null($objType) && $objType) {
            $where['obj_type'] = $objType;
        }
        $list = mObjRelateWiki::getByWhere($where);
        if ($list) {
            foreach ($list as $row) {
                if ($row['type'] == mObjRelateWiki::TYPE_USER_REL && $row['rel_obj_type'] == mObjRelateWiki::REL_OBJ_TYPE_COMMENT) {//评论
                    Log::wiki_cleanedWiki_info('清洗完数据，评论关联wiki#sign:' . json_encode(['wiki_id' => $wikiId]));
                    //更新评论的resId
                    $wikiInfo = \Biz\service\wiki\Wiki::getWikiBaseInfos([$wikiId]);
                    $wikiInfo = ($wikiInfo && isset($wikiInfo[$wikiId])) ? $wikiInfo[$wikiId] : [];
                    if ($wikiInfo) {
                        self::updateCommentLinkResId($wikiInfo, $row['obj_id'], $row['rel_obj_id'], $row['uid']);
                    }
                }
            }
        }
    }

    public static function updateCommentLinkResId($wikiInfo, $objId, $relObjId, $uid)
    {
        if ($wikiInfo) {
            $resId = mShenJianGoods::getInfo($wikiInfo['channel_spu_id'], $wikiInfo['channel_type']);
            if ($resId) {
                $data = [
                    "type" => $wikiInfo['channel_type'],
                    "res_id" => $resId
                ];
                $where = [
                    'obj_id' => $objId,
                    'comments_id' => $relObjId,
                    'ouid' => $uid,
                    'uid' => $uid,
                    'res_id' => 0,
                ];
                mCommentLink::update($data, $where);
            }
        }
    }

    public static function getChannel($type)
    {
        $channel = 0;
        if (in_array($type, [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL])) {
            $channel = mWiki::CHANNEL_TAOBAO;
        } else if ($type == RealUrl::URL_TYPE_JD) {
            $channel = mWiki::CHANNEL_JD;
        } else if ($type == RealUrl::URL_TYPE_YOUZAN) {
            $channel = mWiki::CHANNEL_YOUZAN;
        } else if ($type == RealUrl::URL_TYPE_XIAOEPINPIN) {
            $channel = mWiki::CHANNEL_XIAOEPINPIN;
        } else if ($type == RealUrl::URL_TYPE_AMAZON) {
            $channel = mWiki::CHANNEL_AMAZON;
        } else if ($type == RealUrl::URL_TYPE_XIAOMIYOUPIN) {
            $channel = mWiki::CHANNEL_XIAOMIYOUPIN;
        } else if ($type == RealUrl::URL_TYPE_SAMSUNGESHOP) {
            $channel = mWiki::CHANNEL_SAMSUNGESHOP;
        } else {
            return false;
        }
        return $channel;
    }

    public static function getChannelType($channel)
    {
        $type = 0;
        if ($channel == mWiki::CHANNEL_TAOBAO) {
            $type = mWiki::CHANNEL_TYPE_TAOBAO;
        } else if ($channel == mWiki::CHANNEL_JD) {
            $type = mWiki::CHANNEL_TYPE_JD;
        } else if ($channel == mWiki::CHANNEL_SUNING) {
            $type = mWiki::CHANNEL_TYPE_SUNING;
        } else if ($channel == mWiki::CHANNEL_KAOLA) {
            $type = mWiki::CHANNEL_TYPE_KAOLA;
        } else if ($channel == RealUrl::URL_TYPE_YOUZAN) {
            $type = mWiki::CHANNEL_YOUZAN;
        }
        return $type;
    }

    public static function getDefaultTitle($channelType)
    {
        $title = '';
        $channel = self::getChannel($channelType);
        if ($channel == mWiki::CHANNEL_TAOBAO) {
            $title = '商品链接';
        } else if ($channel == mWiki::CHANNEL_JD) {
            $title = '商品链接';
        }
        return $title;
    }

    /**
     * 获取wiki推荐语
     * @param array $info
     * @return string
     * @throws \Exception
     */
    public static function getWikiRecommendation($info)
    {
        $result = '';
        $buyNum = $info['click_buy_num'];
        $favNum = isset($info['fav_count']) ? $info['fav_count'] : 0;
        $definedIncrement = $info['defined_increment'];
        if ($info['designer_share']) {
            $result = '认证设计师推荐';
        } else if (($buyNum + $favNum + $definedIncrement) > 100) {
            $result = ($buyNum + $favNum + $definedIncrement) . '位住友都想买';
        }
        return $result;
    }


    /**
     * 获取wiki 商品基础信息
     * @param $wikiIds
     * @return array
     */
    public static function getWikiBaseInfos($wikiIds)
    {
        $redis = new newCache(redisKeys::KEY_B_CACHE_WIKI_BASE);
        list($cacheData, $noCacheKeys) = $redis->getCaches($wikiIds);
//        $noCacheKeys = $wikiIds;//缓存debug
        if ($noCacheKeys) {
            $wikiList = mWiki::getInfosByWikiIds($noCacheKeys);
            if (!empty($wikiList)) {
                $redis->setCaches($wikiList);
            }
            $result = $cacheData + $wikiList;
        } else {
            $result = $cacheData;
        }
        return $result;
    }

    public static function getWikiContentInfos($wikiIds)
    {
        $redis = new newCache(redisKeys::KEY_B_CACHE_WIKI_BASE_CONTENT);
        list($cacheData, $noCacheKeys) = $redis->getCaches($wikiIds);
        //$noCacheKeys = $wikiIds;//缓存debug
        if ($noCacheKeys) {
            $wikiList = mWikiContent::getInfosByWikiIds($wikiIds);
            if (!empty($wikiList)) {
                $redis->setCaches($wikiList);
            }
            $result = $cacheData + $wikiList;
        } else {
            $result = $cacheData;
        }
        return $result;
    }

    public static function getRandUserCoverImg($num = 1)
    {
        $imgs = [];
        if ($num) {
            //获取 机器人uid集合
            $uids = Common::getMechanicUids();
            $count = count($uids);
            $num = ($num > $count) ? $count : $num;
            $randIndex = array_rand($uids, $num);
            if (!is_array($randIndex)) {//array_rand num=1 返回非数组
                $randIndex = (array)$randIndex;
            }
            $randUids = [];
            foreach ($randIndex as $index) {
                $randUids[] = $uids[$index];
            }
            list($cacheData, $noCacheKeys) = MechanicUserImg::getImgs($randUids);
            if ($noCacheKeys) {
                $userImgs = [];
                $userList = Member::getUserInfoByIds($noCacheKeys);
                foreach ($userList as $row) {
                    $avatarImgs = User::getUserAvatarPicUrl($row['uid'], $row['avatar_version']);
                    if ($avatarImgs) {
                        MechanicUserImg::setImg($row['uid'], $avatarImgs[0]);
                        $userImgs[$row['uid']] = $avatarImgs[0];
                    }
                }
                $result = $cacheData + $userImgs;
            } else {
                $result = $cacheData;
            }

            foreach ($result as $uid => $coverImg) {
                $imgs[] = ['cover_img' => $coverImg];
            }
        }
        return $imgs;
    }

    /**
     * 获取淘宝客-淘客链接
     * @param $tbItemIdsArr 淘宝商品Id 数组['channel_spu_id'=>'channel_jump_params']
     * @return array
     */
    public static function getTbkLink(array $tbItemIdsArr)
    {
        $result = [];
        $itemIds = array_keys($tbItemIdsArr);
        list($cacheData, $noCacheKeys) = cTbkUrl::mGetItems($itemIds);
        if ($noCacheKeys) {
            foreach ($noCacheKeys as $noCacheKey) {
                $itemId = $noCacheKey;
                $newItemId = $tbItemIdsArr[$itemId];
                $tbkUrl = TbkUnion::getTbkUrl($itemId, $newItemId);
                $result[$itemId] = $tbkUrl;
            }
        }
        foreach ($cacheData as $itemId => $row) {
            $result[$itemId] = $row['url'];
        }
        return $result;
    }

    /**
     * 获取京东联盟-链接
     * @param $itemIds
     * @return array
     */
    public static function getJdUnionLink($itemIds)
    {
        $result = [];
        list($cacheData, $noCacheKeys) = cJdUnionUrl::mGetItems($itemIds);
        if ($noCacheKeys) {
            foreach ($noCacheKeys as $noCacheKey) {
                $jdUrl = JdUnion::tryGetItemUnionUrl($noCacheKey);
                $result[$noCacheKey] = $jdUrl;
            }
        }
        foreach ($cacheData as $itemId => $row) {
            $result[$itemId] = $row['url'];
        }
        return $result;
    }

    /**
     * 获取淘宝客 京东联盟等跳转连接
     * @param $infos
     * @return array
     */
    public static function get3rdInfos($infos)
    {
        $tbItemIdsArr = [];
        $jdItemIds = [];
        foreach ($infos as $key => $row) {
            switch ($row['channel']) {
                case mWiki::CHANNEL_TAOBAO:
                    $tbItemIdsArr[$row['channel_spu_id']] = $row['channel_jump_params'];
                    break;
                case mWiki::CHANNEL_JD:
                    $jdItemIds[] = $row['channel_spu_id'];
                    break;
            }
        }
        $tbkUrlArr = self::getTbkLink($tbItemIdsArr);//淘宝客链接
        $jdUrlArr = self::getJdUnionLink($jdItemIds);//京东联盟链接
        $youzanArr = [];
        foreach ($infos as $wikiId => $info) {
            $tbkUrl = '';
            $jdUrl = '';
            $suningUrl = '';
            $kaolaUrl = '';
            $youzanUrl = '';
            $tbUrl = '';
            $channel_url = '';
            $channel_mini_url = '';
            $channel_app_url = '';
            $weixin_app_id = '';
            switch ($info['channel']) {
                case mWiki::CHANNEL_XIAOMIYOUPIN:
                    $params = http_build_query(['gid' => $info['channel_spu_id'], 'source' => 'haohaozhu', 'feedback' => $info['channel_spu_id']]);
                    $cps = "https://cpsapi.xiaomiyoupin.com/cps/login?";
                    $to = 'https://m.xiaomiyoupin.com/detail?gid=' . $info['channel_spu_id'];
                    $toApp = 'https://m.xiaomiyoupin.com/detail?gid=' . $info['channel_spu_id'] . "&opapp=5";

                    $channel_url = $cps . http_build_query(['source' => 'haohaozhu', 'feedback' => $info['channel_spu_id'], 'to' => $to]);
                    $channel_url = $cps . http_build_query(['source' => 'haohaozhu', 'feedback' => $info['channel_spu_id'], 'to' => $toApp, 'hhzjump' => 1]);

                    $channel_app_url = "youpin://m.xiaomiyoupin.com/detail?gid=" . $info['channel_spu_id'] ?? '';

                    $channel_mini_url = "pages/detail/detail?" . $params;
                    $weixin_app_id = 'gh_6c9e7334fbf6';
                    break;
                case mWiki::CHANNEL_AMAZON:
                    $query = $info['channel_shop_name'] ? "?tag=" . $info['channel_shop_name'] : '';
                    $channel_url = "https://www.amazon.cn/dp/" . $info['channel_jump_params'] . $query;
                    $channel_app_url = "com.amazon.mobile.shopping://www.amazon.cn/products/" . $info['channel_jump_params'] . $query;
                    break;
                case mWiki::CHANNEL_XIAOEPINPIN:
                    $jump = $info['channel_jump_params'] ? json_decode($info['channel_jump_params'], true) : [];
                    $channel_url = $jump['DetailUrl'] ?? '';
                    $channel_app_url = $jump['AppUrl'] ?? '';
                    break;
                case mWiki::CHANNEL_SAMSUNGESHOP:
                    $channel_url = $info['channel_jump_params'] ? ("https://shop.samsung.com.cn/product/" . $info['channel_jump_params']) : '';
                    if ($channel_url) {
                        switch ($info['channel_jump_params']) {
                            case 'QA55LS01CAJXXZ':
                                $channel_url .= '?cid=cn_paid_display_marketing_ctv-ls01c_estore_qa55ls01cajxxz_other_hhz-221012_none';
                                break;
                            case 'QA65LS03CAJXXZ':
                                $channel_url .= '?cid=cn_paid_display_marketing_ctv-ls03c_estore_qa65ls03cajxxz_other_hhz-221012_none';
                                break;
                            case 'QA55LS03CAJXXZ':
                                $channel_url .= '?cid=cn_paid_display_hhz_mktg-ctv_estore_qa55ls03cajxxz_other_230613_none';
                                break;
                            case 'QA55S95ZAJXXZ':
                                $channel_url .= '?cid=cn_paid_display_hhz_mktg-ctv_estore_qa55s95zajxxz_other_230613_none';
                                break;
                            case 'QA75QN900CJXXZ':
                                $channel_url .= '?cid=cn_paid_display_hhz_mktg-ctv_estore_qa75qn900cjxxz_other_230613_none';
                                break;
                        }
                    }
                    break;
                case mWiki::CHANNEL_TAOBAO:
                    $tbUrl = RealUrl::formatLink($info['channel_spu_id'], $info['channel_type']);
                    $tbkUrl = (isset($tbkUrlArr[$info['channel_spu_id']]) && !empty($tbkUrlArr[$info['channel_spu_id']])) ? $tbkUrlArr[$info['channel_spu_id']] : '';
                    if ($tbkUrl) {
                        $channel_url = $tbkUrl;
                    } else {
                        $channel_url = $tbUrl;
                    }
                    $scheme = parse_url($channel_url, PHP_URL_SCHEME);
                    $channel_app_url = str_replace($scheme, "taobao", $channel_url);
//                    if (HhzEnv::isGray()) {
//                        $testArr = [
//                            "617553166087" => "https://c.tb.cn/w3.UGATZ",
//                            "655862209766" => "https://c.tb.cn/w3.UtzoY",
//                            "668553944306" => "https://c.tb.cn/w3.Ux9Tx",
//                            "624608682164" => "https://c.tb.cn/w3.UGwGY",
//                            "596153820497" => "https://c.tb.cn/w3.UGwG1",
//                            "588224389249" => "https://c.tb.cn/w3.UDTmD",
//                            "628125159943" => "https://c.tb.cn/w3.UGmL8",
//                            "626055565515" => "https://m.tb.cn/h.fLgz0su",
//                            "543255335560" => "https://c.tb.cn/w3.UHs12",
//                            "606913571420" => "https://c.tb.cn/w3.UGKLE",
//                            "660244912567" => "https://c.tb.cn/w3.UsUDo",
//                            "654714483461" => "https://c.tb.cn/w3.UGW95",
//                            "580318957199" => "https://c.tb.cn/w3.UwiRy",
//                            "596119832458" => "https://c.tb.cn/w3.UxbvO",
//                            "658941380184" => "https://c.tb.cn/w3.UwiRz",
//                        ];
//                        if (isset($testArr[$info['channel_spu_id']])) {
//                            $channel_url = $testArr[$info['channel_spu_id']];
//                            $channel_app_url = 'taobao://m.taobao.com/tbopen/index.html?h5Url=' . $channel_url;
//                        }
//                    }
                    break;
                case mWiki::CHANNEL_JD:
                    $jdUrl = (isset($jdUrlArr[$info['channel_spu_id']]) && !empty($jdUrlArr[$info['channel_spu_id']])) ? $jdUrlArr[$info['channel_spu_id']] : '';
                    $channel_url = $jdUrl ?: RealUrl::formatLink($info['channel_spu_id'], $info['channel_type']);
                    $data = [
                        "category" => "jump",
                        "des" => "productDetail",
                        "skuId" => $info['channel_spu_id'],
                        "sourceType" => "JSHOP_SOURCE_TYPE",
                        "sourceValue" => "JSHOP_SOURCE_VALUE"
                    ];
                    $data = [
                        "category" => "jump",
                        "des" => "m",
                        "url" => $channel_url,
                        "sourceType" => "JSHOP_SOURCE_TYPE",
                        "sourceValue" => "JSHOP_SOURCE_VALUE",
                        "M_sourceFrom" => "h5auto",
                        "msf_type" => "auto"
                    ];
                    $channel_app_url = trim("openApp.jdMobile://virtual?params=" . json_encode($data));
                    break;
                case mWiki::CHANNEL_SUNING:
                    $suningUrl = SuNing::getItemInfo($info['channel_spu_id']);
                    $channel_url = $suningUrl;
                    break;
                case mWiki::CHANNEL_KAOLA:
                    $kaolaUrl = KaoLa::getItemInfo($info['channel_spu_id']);
                    $channel_url = $kaolaUrl;
                    break;
                case mWiki::CHANNEL_YOUZAN:
                    $channel_url = Youzan::getGoodsUrl($info['channel_jump_params'], $info['channel_shop_id']);
                    $channel_mini_url = "pages/goods/detail/index?alias={$info['channel_jump_params']}";
                    $youzanUrl = $channel_mini_url;
                    $youzanArr[$wikiId] = $info['brand_id'];
                    $weixin_app_id = 'gh_396a6d2e73c5';
                    break;
            }
            $infos[$wikiId]['3rd_link'] = [
                'channel' => $info['channel'],
                'channel_url' => $channel_url,
                'channel_mini_url' => $channel_mini_url,
                'channel_app_url' => $channel_app_url,
                'channel_spu_id' => $info['channel_spu_id'],
                'tbk_pid' => 'mm_394050001_454500301_108710850472',
                'tkUrl' => $tbkUrl,
                'tbUrl' => $tbUrl,
                'jdUrl' => $jdUrl,
                'suningUrl' => $suningUrl,
                'kaolaUrl' => $kaolaUrl,
                'youzanUrl' => $youzanUrl,
                'weixin_app_id' => $weixin_app_id,
            ];
        }
        if ($youzanArr) {
            $brandIds = array_values($youzanArr);
            $brandIds = array_filter(array_unique($brandIds));
            $brandAppList = $brandIds ? BrandAccountInfo::getAllByWhere([
                'type' => BrandAccountInfo::ACCOUNT_TYPE_BRAND,
                'account_status' => BrandAccountInfo::ACCOUNT_STATUS_USED,
                'brand_id' => $brandIds,
                'app_id[!]' => ''
            ], ['brand_id', 'app_name', 'app_channel', 'app_id', 'app_prefix', 'app_shop_id']) : [];
            $brandAppList = $brandAppList ? array_column($brandAppList, null, 'brand_id') : [];
            if ($brandAppList) {
                foreach ($youzanArr as $wikiId => $brandId) {
                    $url = (isset($infos[$wikiId]['3rd_link']['youzanUrl']) && $infos[$wikiId]['3rd_link']['youzanUrl']) ? $infos[$wikiId]['3rd_link']['youzanUrl'] : '';
                    if (isset($brandAppList[$brandId]) && $url) {
                        $infos[$wikiId]['3rd_link']['app_id'] = $brandAppList[$brandId]['app_id'];
                        $infos[$wikiId]['3rd_link']['weixin_app_id'] = $brandAppList[$brandId]['app_id'];
                    }
                }
            }
        }
        return $infos;
    }


    public static function createUnionUrl($tbItemIds, $jdItemIds)
    {
        self::_async($tbItemIds, $jdItemIds);
    }

    public static function _async_createUnionUrl($tbItemIdsArr, $jdItemIds)
    {
        if ($tbItemIdsArr) {
            clsWiki::getTbkLink($tbItemIdsArr);
        }
        if ($jdItemIds) {
            clsWiki::getJdUnionLink($jdItemIds);
        }
    }

}